package org.pupil.socket.serialization.fastjson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import org.pupil.socket.serialization.Serialization;

import java.io.IOException;

/**
 * @Description: json序列化方式
 * @Author: pupil
 * @Date: 2024/07/07 下午 1:20
 */
public class JsonSerialization implements Serialization {
    @Override
    public <T> byte[] serialize(T obj) throws IOException {
        try {
            // 使用Fastjson将对象序列化为json字符串
            String jsonString = JSON.toJSONString(obj);
            // 将json字符串转换成字节数组返回
            return jsonString.getBytes("UTF-8");
        } catch (JSONException e) {
            // 捕获序列化过程中可能发生的异常
            throw new IOException("Error serializing object to JSON", e);
        }

    }

    @Override
    public <T> T deSerialize(byte[] data, Class<T> clazz) throws IOException {
        try {
            // 将字节数组转换为json字符串
            String jsonString = new String(data,"UTF-8");
            // 将json字符串转换为对象
            return JSON.parseObject(jsonString,clazz);
        } catch (JSONException e) {
            // 捕获反序列化过程中可能发生的异常
            throw new IOException("Error deserializing JSON to Object", e);
        }
    }
}
